package cn.swust.designpatternlearningplatform.listener;

import cn.swust.designpatternlearningplatform.common.utils.PasswordManger;
import cn.swust.designpatternlearningplatform.dao.ClassManagementDao;
import cn.swust.designpatternlearningplatform.dao.StudentDao;
import cn.swust.designpatternlearningplatform.domain.entity.Student;
import cn.swust.designpatternlearningplatform.domain.vo.StudentVo;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;


import java.util.List;


@Slf4j
public class DemoDataListener implements ReadListener<StudentVo> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<Student> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private StudentDao studentDao;
    private ClassManagementDao classManagementDao;
    private String teacherAccount;
    private String semester;


    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param studentDao
     */
    public DemoDataListener(StudentDao studentDao, ClassManagementDao classManagementDao, String teacherAccount, String semester) {
        this.studentDao = studentDao;
        this.classManagementDao = classManagementDao;
        this.teacherAccount = teacherAccount;
        this.semester = semester;
    }

    @Override
    public void invoke(StudentVo student, AnalysisContext analysisContext) {
        Student student1 = new Student();
        BeanUtils.copyProperties(student, student1);
        cachedDataList.add(student1);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        for (int i = 0; i < cachedDataList.size(); i++) {
            Student student = cachedDataList.get(i);
            Student student1 = studentDao.getStudentByNumber(student.getStudentNumber());
            if (student1 == null) {
                student.setStudentPassword(PasswordManger.pwdDigest("123456"));
                student.setTeacherAccount(teacherAccount);
                student.setSemester(semester);
                // System.out.println(student);
                classManagementDao.AddStudent(student);
            }
        }
        log.info("存储数据库成功！");
    }
}